package com.dd.keel.core.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Error code util
 * @author Kevin.Xu
 *
 */
public class ErrorCode {
	
	final static private Logger LOGGER = LoggerFactory.getLogger(ErrorCode.class);
	
	Properties props = new Properties();
	
	private volatile static HashMap<String,ErrorCode> instancesMap = new HashMap<String,ErrorCode>();
	
	private static String DEFAULT_ERROR_CODE_FILE = "error-code.properties";
	
	public static ErrorCode getInstance(Class contextClass,String filename)
	{
		if(!instancesMap.containsKey(filename))
		{
			synchronized(ErrorCode.class)
			{
				if(!instancesMap.containsKey(filename))
				{
					instancesMap.put(filename, new ErrorCode(contextClass,filename));
				}
			}
		}
		return instancesMap.get(filename);
	}
	
	public static ErrorCode getInstance(Class contextClass)
	{
		return getInstance(contextClass,DEFAULT_ERROR_CODE_FILE);
	}
	
	private ErrorCode(Class contextClass,String filename)
	{
		InputStream error_code_inputstream = null;
		String error_code_config_file = FileUtil.retrieveConfigFilepath(filename);
		File error_code_file = new File(error_code_config_file);
		if(error_code_file.exists())
		{
			LOGGER.debug("ErrorCode :: etc/{} exist!", filename);
			try {
				error_code_inputstream = new FileInputStream(error_code_file);
			} catch (FileNotFoundException ex) {
				LOGGER.error( ex.getMessage(), ex );
			}
		}
		else
		{
			LOGGER.debug("ErrorCode :: etc/{} not exist!", filename);
			LOGGER.debug("ErrorCode :: try to find {} from classpath ...", filename);
			try {
				error_code_inputstream = URLUtil.getURLFromClasspath(filename,contextClass).openStream();
			} catch (IOException ex) {
				LOGGER.error( ex.getMessage(), ex );
			} catch (Exception ex) {
				LOGGER.error( ex.getMessage(), ex );
			}
		}
		if(error_code_inputstream==null)
		{
			LOGGER.error("ErrorCode :: Can not find {}", filename);
			return;
		}
		try{
			props.load( error_code_inputstream );
		}catch(Exception ex){
			LOGGER.error( ex.getMessage(), ex );
		}
		if(error_code_inputstream!=null)
		{
			try {
				error_code_inputstream.close();
			} catch (IOException ex) {
				LOGGER.error( ex.getMessage(), ex );
			}
		}
	}
	
	public String getErrorMsg(String category,int errorCode)
	{
		String key = category + "." + errorCode;
		if(props.getProperty(key)==null)
		{
			return "";
		}
		return props.getProperty(key).trim();
	}
	
}
